package WebSocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.internal.logging.InternalLogLevel;
import org.springframework.stereotype.Component;
import WebSocket.Handler;

import java.util.concurrent.TimeUnit;

import static WebSocket.Constants.readerIdleTime;

/**
 * websocket初始化类
 */
@Component
public class WebSocketServerInitializer extends ChannelInitializer<Channel> {


    private Handler heartBeatHandler=new Handler() ;


    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast(new IdleStateHandler(readerIdleTime, 0, 0, TimeUnit.SECONDS));
        //websocket协议本身是基于http协议的，所以这边也要使用http解编码器
        pipeline.addLast(new HttpServerCodec());
        //ChunkedWriteHandler分块写处理，文件过大会将内存撑爆
        pipeline.addLast(new ChunkedWriteHandler());
        //netty是基于分段请求的，HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
        pipeline.addLast(new HttpObjectAggregator(665536));
        pipeline.addLast(new LoggingHandler(String.valueOf(InternalLogLevel.INFO)));

        //ws://server:port/context_path
        //ws://localhost:9999/ws
        //参数指的是context_path
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 665535));

        //websocket定义了传递数据的6中frame类型
        pipeline.addLast(heartBeatHandler);

    }


}
